package com.bd.scm.module.oauth2;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "O2Callback", urlPatterns = {"/callback"})
public class O2Callback extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain;charset=UTF-8");
        // 保存最终要跳转的地址
        String target = request.getParameter("target_uri");
        PrintWriter out = response.getWriter();
        String url = "https://portal.hascovision.com/profile/oauth2/accessToken?client_id=CbtEGup0dHNO8W0B&code="
                + request.getParameter("code")
                + "&client_secret=Wzsuh1BB1dT8vuxWYnO62gwoVQBCjhmZ&redirect_uri="
                + URLEncoder.encode(target, "utf-8");
        String res = HttpUtil.httpPost(url, "");
        String token = res.substring(res.indexOf('=') + 1, res.indexOf('&'));
        url = "https://portal.hascovision.com/profile/oauth2/profile?access_token=" + token;
        res = HttpUtil.httpPost(url, "");
        // 返回格式是json的，解析后若成功则生成用户信息并跳转到目标地址，若失败提醒失败信息
        // 此信息仅用于本地，并且不和服务器互动，格式根据每套系统自身要求产生
        // request.getSession().setAttribute("user", "xxx");
        // response.sendRedirect(target);
        // 此处应跳转至Home，作为演示仅显示账号信息
        out.write(res);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Oauth2 callback";
    }
}
